package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 过滤器作用 统一拦截请求进行判断
 */
@Component
@Order(-1) //可以不加 也可以实现order
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、拿到请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2、判断本次是否是登录相关资源 登录则放行
        if (request.getURI().getPath().contains("/login")) {
            //放行
            return chain.filter(exchange);
        }
        //3、不是登录 进行token验证
        //3.1、获取到token (不止一个token)getFirst
        try {
            String token = request.getHeaders().getFirst("token");
            //3.2、验证token是否有效 a、不能为空；b、不能过期；c、不能报错（伪造token）
            if (StringUtils.isBlank(token)) {
                // 为空
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();

            }
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int res = AppJwtUtil.verifyToken(claimsBody);
            if (res == 1 || res == 2) {
                // 过期
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            // 没过期，将token解析得到用户id，并且存入request的请求头哦header中，供后面的微服务使用
            Object userId = claimsBody.get("id");
            //在header中添加信息
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders ->
                    httpHeaders.add("userId", userId.toString())).build();
            //重置header
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            e.printStackTrace();
            // 伪造token
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }

        //4、到这 就放行
        return chain.filter(exchange);

    }
}
